package com.cqupt.scanning.security.utils;

import com.cqupt.scanning.security.config.JwtSecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.security.Key;
import java.util.Date;

/**
 * @Description:
 * @ClassName: JwtTokenUtil
 * @Date: 2021/1/6 15:50
 * @Author: 宋宝梁
 */

@Component
public class JwtTokenUtil {

    private static Key key;

    private static JwtSecurityProperties jwtSecurityProperties;
    public JwtTokenUtil(JwtSecurityProperties jwtSecurityProperties) {
        JwtTokenUtil.jwtSecurityProperties = jwtSecurityProperties;
    }

    // @Postcontruct在依赖注入完成后自动调用
    @PostConstruct
    public static void init() {
        try {
            // 对令牌进行base64编码
            byte[] keyBytes = Decoders.BASE64.decode(jwtSecurityProperties.getBase64Secret());
            // 根据指定的密钥字节数组创建一个新的SecretKey实例，以供HMAC-SHA算法使用。
            key = Keys.hmacShaKeyFor(keyBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String generateToken(String subject) {
        return Jwts.builder()
                .setClaims(null)
                .setSubject(subject)
                .setExpiration(new Date(System.currentTimeMillis() + jwtSecurityProperties.getTokenValidityInSeconds() * 1000))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    public String parseToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    public void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

}
